/**
 * 单纯插值语法处理
 */

import { type GoGoAST } from "gogocode";
import { CommonParams, IGoGoCodeNode } from "../../types";
import { genKey, updateLocalesFile } from "../../utils/file";
import { hasChinese, isChinese } from "../../utils/check";

/**
 * 单纯插值语法处理
 */
const handleChildNode = ({
  sfcAst,
  CONFIG,
  logger,
  filePath,
}: CommonParams & { sfcAst: GoGoAST }): GoGoAST => {
  const { I18N_FUNC, CHINESE_REGEX: CRG } = CONFIG;
  const getKey = (text: string) =>
    updateLocalesFile({
      text,
      CONFIG,
      logger,
      filePath,
    });
  return sfcAst
    .find(`<template></template>`)
    .find(`<$_$>$$$0</$_$>`)
    .each((item) => {
      // 获取子节点
      const children = item.match["$$$0"] as unknown as IGoGoCodeNode[];
      // 处理子节点
      children.forEach(({ nodeType, content: { value } }) => {
        const originText = value?.content || "";
        if (
          nodeType === "text" &&
          value &&
          originText.trim() !== "" &&
          hasChinese(originText, CRG)
        ) {
          // 插值语法
          if (originText.includes("{{") && originText.includes("}}")) {
            const REG = new RegExp(`(\\'|\\")([\\w${CRG}]+)\\1`);
            let tempStr = originText;
            const strList: string[] = [];
            // 按插值语法分割原始字符串
            while (tempStr.length) {
              const matched = [...tempStr.matchAll(/\{\{[\s\S]+?\}\}/g)];
              if (matched.length === 0) {
                strList.push(tempStr);
                break;
              }
              const match = matched?.[0];
              if (match && match[0]) {
                const prev = tempStr.slice(0, match.index);
                if (prev) {
                  strList.push(prev);
                }
                strList.push(match[0]);
                tempStr = tempStr.slice(match.index + match[0].length);
              }
            }
            value.content = strList.reduce((prev, str) => {
              if (hasChinese(str, CRG)) {
                if (str.startsWith("{{") && str.endsWith("}}")) {
                  return (prev += str.replace(REG, (_, p1, p2) => {
                    const key = getKey(p2.trim());
                    return `${I18N_FUNC}('${key}')`;
                  }));
                } else {
                  const key = getKey(str.trim());
                  return (prev += `{{ ${I18N_FUNC}('${key}') }}`);
                }
              }
              return (prev += str);
            }, "");
          } else {
            // 纯文本
            const noSpaceText = originText.trim();
            const REG =
              noSpaceText.length === 1
                ? new RegExp(`[\\w${CRG}]`)
                : new RegExp(`[\\w${CRG}][\\w${CRG} ]*[\\w${CRG}]`);
            const tempStr = originText.replace(REG, (match) => {
              const key = getKey(match);
              return `{{ ${I18N_FUNC}('${key}') }}`;
            });
            value.content = tempStr;
          }
        }
      });
    })
    .root();
};

export default handleChildNode;
